import logging

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class DouyinMerge(models.Model):
    """合并的视频
    """
    _name = 'douyin.merge'
    _description = '合并的视频'
    _rec_name = 'collection_id'

    alias = fields.Char(related='collection_id.alias')
    collection_id = fields.Many2one(comodel_name='douyin.collection', string='合集')
    create_time = fields.Datetime(string='创建时间', default=fields.Datetime.now)
    start = fields.Integer(string='开始集数')
    end = fields.Integer(string='结束集数')
    state = fields.Selection(
        string='状态',
        selection=[
            ('draft', '未开始'),
            ('ready', '已准备'),
            ('ongoing', '制作中'),
            ('done', '已完成'),
            ('error', '异常')
        ],
        default='draft'
    )
    video_ids = fields.One2many(comodel_name='douyin.video', inverse_name='merge_id', string='包含的视频')
    hours = fields.Float(string='时长(小时)', compute='_compute_hours')
    celery_task_id = fields.Many2one(comodel_name='celery.task', string='Celery任务')

    @api.depends('video_ids')
    def _compute_hours(self):
        for rec in self:
            rec.hours = round(sum(rec.video_ids.mapped('duration'))/3600000, 2)

    def action_merge_collection(self):
        if self:
            task_sequence = self.env['celery.task.sequence'].create({
                'sequence_type': 'collection_merge'
            })
            for merge in self.filtered(lambda r: r.state == 'ready'):
                task = self.env['celery.task'].create({
                    'task_type': 'collection_merge',
                    'sequence_id': task_sequence.id
                })
                merge.celery_task_id = task.id

            task_sequence.action_run_sequence()
            self.update({'state': 'ongoing'})
        else:
            raise UserError('没有【已准备】合集，请检查')